package com.sgb.member.view_model;

import android.text.TextUtils;
import android.view.View;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.lxj.xpopup.XPopup;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ApplyCompanyBean;
import com.sgb.member.entity.CompanyDeptBean;
import com.sgb.member.entity.MInviteEntity;
import com.sgb.member.entity.MemberApprovalBean;
import com.sgb.member.entity.MemberProfileBean;
import com.sgb.member.entity.ProcessBean;
import com.sgb.member.entity.QualityMemberBean;
import com.sgb.member.entity.ThresholdParamBean;
import com.sgb.member.entity.UserMsgEntity;
import com.sgb.member.ui.activity.MemberApplyJoinActivity;
import com.sgb.member.weight.MultiMemberChoosePopup;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.UploadFileBean;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * Created by：冯齐 on 2021/1/5 09:55
 * Description：
 */
public class MemberApplyJoinModel extends BaseViewModel {
    private final MemberApplyJoinActivity activity;
    private final MemberRepertory mRepertory;

    public MemberApplyJoinModel(MemberApplyJoinActivity activity, MemberRepertory repertory) {
        this.activity = activity;
        this.mRepertory = repertory;
    }

    /**
     * 邀请加盟企业列表
     */
    public void invitedCom(MInviteEntity entity) {
        DialogHelper.showProgressDialog(activity, "邀请中...");
        mRepertory.getApi().memberJoin(entity).enqueue(new ICallBack<BaseEntity<BaseEntity<String>>>() {
            @Override
            public void onSuccess(BaseEntity<BaseEntity<String>> data) {
                if (data.getData().getCode().equals("0")) {
                    activity.inviteSuccess();
                } else {
                    MToast.showToast(activity, data.getData().getMsg());
                }
            }
        });
    }


    //  ascription 1 供方 0需方
    public void getThresholdByMemberType(String companyNo, String relation, Object... objects) {
        DialogHelper.showProgressDialog(activity, "邀请中...");
        Map<String, Object> map = new HashMap<>();
        map.put("businessNo", companyNo);
        map.put("relation", TextUtils.equals("0", relation) ? "1" : "2"); // 	供需关系1:供方2:需方
        if (objects.length > 0) {
            List<String> no1 = new ArrayList<>();
            no1.add(((CommonPopEntity) objects[0]).getNo());
            map.put("firstCategoryNos", no1);
        }
        if (objects.length > 1) {
            List<String> no2 = new ArrayList<>();
            no2.add(((CommonPopEntity) objects[1]).getNo());
            map.put("secondCategoryNos", no2);
        }
        if (objects.length > 2) {
            List<String> no3 = new ArrayList<>();
            no3.add(((CommonPopEntity) objects[2]).getNo());
            map.put("thirdCategoryNos", no3);
        }
        mRepertory.getApi().getThresholdByMemberType(map).enqueue(new ICallBack<BaseEntity<List<ThresholdParamBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ThresholdParamBean>> data) {
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    activity.getThresholdByMemberType(data.getData());
                }
            }
        });
    }

    public void uploadSingleFile(UploadFileBean item) {
        DialogHelper.showProgressDialog(activity, "文件上传中...");
        File file = new File(item.getFilePath());
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"file." + item.getExtension(), requestBody);
        mRepertory.getApi().uploadFile(photos).enqueue(new ICallBack<BaseEntity<String>>() {
            @Override
            public void onSuccess(BaseEntity<String> data) {
                item.setUrlPath(data.getData());
                activity.setUploadFileUrl(item);
            }
        });
    }


    public void sendApprove(MemberApprovalBean bean) {
        DialogHelper.showProgressDialog(activity, "邀请中...");
        mRepertory.getApi().sendApprove(bean).enqueue(new ICallBack<BaseEntity<BaseEntity>>() {
            @Override
            public void onSuccess(BaseEntity<BaseEntity> data) {
                if (data.getData().getCode().equals("0")) {
                    activity.inviteSuccess();
                } else {
                    MToast.showToast(activity, data.getData().getMsg());
                }
            }
        });
    }

    /**
     * 获取审批流程状态
     * <p>
     * 邀请加盟审批类型 inviteJoinCompany
     * 申請加盟审批类型 applyJoinCompany
     * 会员企业调级 memberEvaluate
     * 会员解除申请 memberRelieve
     */
    public void getProcessStatus(String companyNo, String approveType) {
        DialogHelper.showProgressDialog(activity, "数据加载中...");
        mRepertory.getApi().getProcessStatus(companyNo, approveType).enqueue(new ICallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                // "status": "1" //1 表示有审批 0 代表无审批
                String status = ((Map<String, String>) data.getData()).get("status");
                if (!TextUtils.isEmpty(status)) {
                    activity.updateProcessStatus(status);
                } else {
                    MToast.showToast(activity, "网络异常，请稍后重试");
                    DialogHelper.dismissProgressDialog();
                    activity.showEmptyView();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                super.onFailure(call, t);
                DialogHelper.dismissProgressDialog();
                activity.showEmptyView();
            }

            @Override
            public void onFinally() {

            }
        });
    }

    public void getCompanyProfile(String companyId) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(activity, "数据获取中...");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("companyNo", companyId);
        mRepertory.getApi().getCompanyWebProfile(map).enqueue(new ICallBack<BaseEntity<MemberProfileBean>>() {
            @Override
            public void onSuccess(BaseEntity<MemberProfileBean> data) {
                if (data != null && data.getData() != null) {
                    activity.setMemberProfile(data.getData());
                } else {
                    activity.showEmptyView();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MemberProfileBean>> call, Throwable t) {
                super.onFailure(call, t);
                activity.showEmptyView();
            }

        });
    }

    public void getProcessData(QualityMemberBean bean) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(activity, "数据获取中...");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("processId", bean.getProcessId());
        mRepertory.getApi().getProcessData(map).enqueue(new ICallBack<BaseEntity<ProcessBean>>() {
            @Override
            public void onSuccess(BaseEntity<ProcessBean> data) {
                if (data != null && data.getData() != null) {
                    ProcessBean processBean = data.getData();
                    activity.setInviteRecordDetail(processBean, processBean.getData().getData());
                } else {
                    activity.showEmptyView();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ProcessBean>> call, Throwable t) {
                super.onFailure(call, t);
                activity.showEmptyView();
            }
        });
    }

    public void getJoinEditDetail(QualityMemberBean bean) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(activity, "数据获取中...");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("no", bean.getNo());
        /*map.put("relation", bean.getMemberRelation());*/
        mRepertory.getApi().getEditDetail(map).enqueue(new ICallBack<BaseEntity<MInviteEntity>>() {
            @Override
            public void onSuccess(BaseEntity<MInviteEntity> data) {
                if (data != null && data.getData() != null) {
                    activity.setInviteRecordDetailAndNoApproval(data.getData());
                } else {
                    activity.showEmptyView();
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MInviteEntity>> call, Throwable t) {
                super.onFailure(call, t);
                activity.showEmptyView();
            }
        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(activity, "数据获取中...");
        mRepertory.getApi().getUserInfo().enqueue(new ICallBack<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onSuccess(BaseEntity<UserMsgEntity> data) {
                // activity.setUserInfo(data.getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                super.onFailure(call, t);
                activity.showEmptyView();
            }
        });
    }

    //获取h5链接
    public void companyInfoDetail(QualityMemberBean memberBean) {
        DialogHelper.showProgressDialog(activity, "数据加载中...").setCanceledOnTouchOutside(false);
        mRepertory.getApi().getUrlSetting("companyInfoDetail").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                String url = data.getData().getUrl() + "?id=" + memberBean.getCompanyId();// isExamine从会员审核列表进入传1
                MemberConfig.getInstance().startWebViewX5(activity, url, 101);
            }
        });
    }

    private ApplyCompanyBean companyBean;

    // 审批【申请】企业列表
    public void getMyCompanyList(ItemInputTextView textView, SimpleResult<CompanyDeptBean> simpleResult) {
        DialogHelper.showProgressDialog(activity, "数据获取中...");
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        mRepertory.getApi().getMyCompanyList().enqueue(new ICallBack<BaseEntity<List<ApplyCompanyBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ApplyCompanyBean>> data) {
                if (data != null && data.getData() != null) {
                    for (int i = 0; i < data.getData().size(); i++) {
                        ApplyCompanyBean bean = data.getData().get(i);
                        if (companyNo.equals(bean.getComNo())) {
                            companyBean = bean;
                            getDeptList(textView, simpleResult);
                            return;
                        }
                    }
                }
                MToast.showToast(textView.getContext(), "申请部门为空");
            }
        });
    }

    // 审批【申请】部门列表
    public void getDeptList(ItemInputTextView textView, SimpleResult<CompanyDeptBean> simpleResult) {
        DialogHelper.showProgressDialog(activity, "数据获取中...");
        if (companyBean == null) {
            getMyCompanyList(textView, simpleResult);
            return;
        }
        mRepertory.getApi().getDeptList(companyBean.getId()).enqueue(new ICallBack<BaseEntity<List<CompanyDeptBean>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CompanyDeptBean>> data) {
                List<CompanyDeptBean> tempList = data.getData();
                if (tempList != null && tempList.size() > 0) {
                    mPop3 = new ArrayList<>();
                    mPop3.addAll(tempList);
                    showDepttPop(textView, simpleResult);
                } else {
                    MToast.showToast(textView.getContext(), "申请部门为空");
                }
            }
        });
    }

    // 会员等级
    public void getMemberLevelList(ItemInputTextView textView, SimpleResult<CommonPopEntity> simpleResult) {
        DialogHelper.showProgressDialog(activity, "数据获取中...");
        mRepertory.getApi().getMemberLevelList().enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                List<CommonPopEntity> tempList = data.getData();
                if (tempList != null && tempList.size() > 0) {
                    if (tempList.get(0).getTypeName().equals("全部")) {
                        tempList.remove(0);
                    }
                    mPop4 = new ArrayList<>();
                    mPop4.addAll(tempList);
                    showMemberLeverPop(textView, simpleResult);
                }
            }
        });
    }

    private List<CompanyDeptBean> mPop3;

    public void showDepttPop(ItemInputTextView textView, SimpleResult<CompanyDeptBean> simpleResult) {
        if (mPop3 == null) {
            getDeptList(textView, simpleResult);
            return;
        }
        OptionsPickerView<CompanyDeptBean> mOption3 = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String name = mPop3.get(options1).getName();
                String id = mPop3.get(options1).getId();
                textView.setContent(name);
                // 申请部门
                /*levelBean.setApplyDeptNo(id);
                levelBean.setApplyDeptName(name);*/
                if (simpleResult != null) {
                    simpleResult.onResult(mPop3.get(options1));
                }
            }
        }).setCancelColor(activity.getResources().getColor(R.color.color_title_small)).setLineSpacingMultiplier(2.2f)
                .setCancelColor(0xFF666666).setTitleColor(0xFF969696).setSubCalSize(15).setTitleSize(15)
                .setContentTextSize(15)
                .build();
        mOption3.setTitleText("申请部门");
        mOption3.setPicker(mPop3);
        mOption3.setSelectOptions(0);
        mOption3.show();
    }

    private List<CommonPopEntity> mPop4;

    public void showMemberLeverPop(ItemInputTextView textView, SimpleResult<CommonPopEntity> simpleResult) {
        if (mPop4 == null) {
            getMemberLevelList(textView, simpleResult);
            return;
        }
        OptionsPickerView<CommonPopEntity> mOption4 = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String name = mPop4.get(options1).getPickerViewText();
                textView.setContent(name);
                if (simpleResult != null) {
                    simpleResult.onResult(mPop4.get(options1));
                }
            }
        }).setCancelColor(activity.getResources().getColor(R.color.color_title_small)).setLineSpacingMultiplier(2.2f)
                .setCancelColor(0xFF666666).setTitleColor(0xFF969696).setSubCalSize(15).setTitleSize(15)
                .setContentTextSize(15)
                .build();
        mOption4.setTitleText("会员等级");
        mOption4.setPicker(mPop4);
        mOption4.setSelectOptions(0);
        mOption4.show();
    }

    private OptionsPickerView<CommonPopEntity> mOption5;
    private List<CommonPopEntity> mPop5;

    public void showSupplyDemandPop(ItemInputTextView textView, SimpleResult<CommonPopEntity> simpleResult) {
        if (mOption5 == null) {
            // 供需关系  1供方  2需方
            mPop5 = new ArrayList<>();
            mPop5.add(new CommonPopEntity("1", "供方会员"));
            mPop5.add(new CommonPopEntity("2", "需方会员"));
            mOption5 = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    String no = mPop5.get(options1).getNo();
                    String name = mPop5.get(options1).getTypeName();
                    textView.getContent_edt().setText(name);
                    if (simpleResult != null) {
                        simpleResult.onResult(mPop5.get(options1));
                    }
                }
            }).setCancelColor(activity.getResources().getColor(R.color.color_title_small)).setLineSpacingMultiplier(2.2f)
                    .setCancelColor(0xFF666666).setTitleColor(0xFF969696).setSubCalSize(15).setTitleSize(15)
                    .setContentTextSize(15)
                    .build();
            mOption5.setTitleText("供需关系");
        }
        mOption5.setPicker(mPop5);
        mOption5.setSelectOptions(0);
        mOption5.show();
    }

    // 会员类型
    private String mAscription = "";

    public void getMemberTypeList(int height, String ascription,String businessNo, SimpleResult<CommonPopEntity> simpleResult) {
        if (TextUtils.equals(mAscription, ascription) && mTypeData != null) {
            showMemberTypePopup(height, mTypeData, simpleResult);
            return;
        }
        DialogHelper.showProgressDialog(activity, "数据获取中...");
        // 0 供方 1需方
        mRepertory.getApi().getMemberTypeList2(ascription,businessNo).enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null && data.getData().size() > 0) {
                    data.getData().add(0, new CommonPopEntity("", "全部"));
                    mAscription = ascription;
                    showMemberTypePopup(height, data.getData(), simpleResult);
                }
            }
        });
    }

    private List<CommonPopEntity> mTypeData;

    private void showMemberTypePopup(int height, List<CommonPopEntity> data, SimpleResult<CommonPopEntity> simpleResult) {
        // 0 供方 1需方
        mTypeData = new ArrayList<>();
        mTypeData.addAll(data);
        MultiMemberChoosePopup choosePopup = new MultiMemberChoosePopup(activity, height, mTypeData, "会员类型", null) {
            @Override
            public void onResult(CommonPopEntity t, Object... objects) {
                simpleResult.onResult(t, objects);
            }
        };
        new XPopup.Builder(activity)
                .asCustom(choosePopup).show();
    }
}
